package mspbots.autotask.data.core.projects;


import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;


@Log4j2
@Component
@RequiredArgsConstructor
public class ProjectsReceiver {

    private final ProjectsRepository projectsRepository;


    @RabbitListener(queues = "auto-task.projects.sync")
    public void syncTask(ResultMsg content) {

        Project project = Project.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
//                .createdTime(LocalDateTime.parse(content.getEntity().get("createDateTime").textValue(),
//                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
//                .updatedTime(LocalDateTime.parse(content.getEntity().get("lastActivityDateTime").textValue(),
//                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(project.getOtherId())) {
            return;
        }

        this.projectsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(oldProject -> {
                    project.setId(oldProject.getId());
                    return project;
                })
                .defaultIfEmpty(project)
                .flatMap(this.projectsRepository::save).block(Duration.ofSeconds(10));

    }
}
